import { getIndustryDynamic } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useDynamicsStore = defineStore('DynamicsStore', () => {
  const dynamicsSets = ref<any[]>([]);
  const loading = ref<boolean>(false);
  const dynamicsPage = ref({
    currentPage: 1,
    total: 0,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
  });

  const updateDynamicsSets = async (term?: string) => {
    loading.value = true;
    const req = {
      pageNo: dynamicsPage.value.currentPage,
      pageSize: dynamicsPage.value.pageSize,
      searchTerm: term || undefined,
    };
    if (term) {
      req.pageNo = 1;
    }
    const res = await getIndustryDynamic(req);
    const { data, meta } = res;

    dynamicsSets.value = data.map((item: any) => ({
      id: item.id,
      title: item.attributes.title,
      time: item.attributes.time,
    }));
    dynamicsPage.value.total = meta.pagination.total;

    if (term) {
      if (meta.pagination.total > 0) {
        ElMessage.success(`搜索'${term}'成功，共 ${meta.pagination.total} 条行业动态数据`);
      } else {
        ElMessage.warning(`暂无'${term}'行业动态数据`);
      }
    }
    loading.value = false;
  };

  // 设置分页信息
  const setDynamicsSetsPage = (page?: number) => {
    if (page) dynamicsPage.value.currentPage = page;
  };

  const getDynamicsSets = computed(() => {
    return dynamicsSets.value;
  });

  const getPlantPage = computed(() => {
    return dynamicsPage.value;
  });

  const pagination = computed(() => ({
    current: dynamicsPage.value.currentPage,
    total: dynamicsPage.value.total,
    pageSize: dynamicsPage.value.pageSize,
    onChange: (page: number) => {
      setDynamicsSetsPage(page);
      updateDynamicsSets().then();
    },
  }));

  const getDynamicsLoading = computed(() => {
    return loading.value;
  });

  return {
    updateDynamicsSets,
    getDynamicsSets,
    setDynamicsSetsPage,
    getPlantPage,
    pagination,
    getDynamicsLoading,
  };
});
